package cn.wowjoy.office.materialinspection.check.detail;

import android.arch.lifecycle.Observer;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.Html;
import android.view.Gravity;
import android.view.View;
import android.widget.PopupWindow;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import cn.wowjoy.office.R;
import cn.wowjoy.office.baselivedata.appbase.LiveDataWrapper;
import cn.wowjoy.office.baselivedata.appbase.NewBaseActivity;
import cn.wowjoy.office.common.widget.AlphaManager;
import cn.wowjoy.office.common.widget.BottomMenuPopupExist;
import cn.wowjoy.office.common.widget.CreateDialog;
import cn.wowjoy.office.common.widget.MDialog;
import cn.wowjoy.office.data.request.SubmitCheckTaskListDetailRequest;
import cn.wowjoy.office.data.response.CheckBroadResultResponse;
import cn.wowjoy.office.data.response.InventoryTaskDtlVO;
import cn.wowjoy.office.data.response.InventoryTaskListDtlResponse;
import cn.wowjoy.office.databinding.ActivityCheckDetailBinding;
import cn.wowjoy.office.materialinspection.check.task.abnormal.AbNormalActivity;
import cn.wowjoy.office.utils.MD5Util;
import cn.wowjoy.office.utils.MyTextWatcher;
import cn.wowjoy.office.utils.ToastUtil;

public class CheckDetailActivity extends NewBaseActivity<ActivityCheckDetailBinding, CheckDetailViewModel> implements View.OnClickListener {

    private boolean isDone;
    private String taskDtlId;
    private MDialog waitDialog;

    private BottomMenuPopupExist mMenuPop;//下拉框
    private String taskId;//总任务ID
    MDialog mDialog;
    private SubmitCheckTaskListDetailRequest request;//提交参数实体

    private InventoryTaskDtlVO data; //当前展示实体

    @Override
    protected Class<CheckDetailViewModel> getViewModel() {
        return CheckDetailViewModel.class;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_check_detail;
    }

    @Override
    protected void init(Bundle savedInstanceState) {
        binding.setViewModel(viewModel);
        initView();
        initListener();
        initObserve();
    }

    private void initObserve() {
        viewModel.getBroadResult().observe(this, new Observer<LiveDataWrapper<CheckBroadResultResponse>>() {
            @Override
            public void onChanged(@Nullable LiveDataWrapper<CheckBroadResultResponse> submitCheckTaskListDetailResponseLiveDataWrapper) {
                switch (submitCheckTaskListDetailResponseLiveDataWrapper.status) {
                    case LOADING:
                        waitDialog = CreateDialog.waitingDialog(CheckDetailActivity.this);
                        break;
                    case SUCCESS:
                        waitDialog.dismiss();
                        //强提示  弹框表示
                        if (null != submitCheckTaskListDetailResponseLiveDataWrapper.data && "该设备不在本次盘点范围内".equals(submitCheckTaskListDetailResponseLiveDataWrapper.data.getInfo())) {
                            Intent intent = new Intent(CheckDetailActivity.this, AbNormalActivity.class);
                            intent.putExtra("error", 1);
                            intent.putExtra("data", submitCheckTaskListDetailResponseLiveDataWrapper.data);
                            startActivity(intent);
                            finish();
                        } else if (null != submitCheckTaskListDetailResponseLiveDataWrapper.data && "N".equalsIgnoreCase(submitCheckTaskListDetailResponseLiveDataWrapper.data.getInSystem())) {
                            Intent intent = new Intent(CheckDetailActivity.this, AbNormalActivity.class);
                            intent.putExtra("error", 0);
                            startActivity(intent);
                            finish();
                        } else {
                            mDialog = CreateDialog.submitDialog(CheckDetailActivity.this, "盘点成功",  submitCheckTaskListDetailResponseLiveDataWrapper.data.getInfo(), 102, new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    if (null != mDialog) {
                                        mDialog.cancel();
                                    }
                                    finish();
                                }
                            }, "好的");
                        }
                        break;
                    case ERROR:
                        waitDialog.dismiss();
                        Throwable throwable = submitCheckTaskListDetailResponseLiveDataWrapper.error;
                        handleException(throwable, false);
                }
            }
        });


        viewModel.getResponse().observe(this, new Observer<LiveDataWrapper<InventoryTaskListDtlResponse>>() {
            @Override
            public void onChanged(@Nullable LiveDataWrapper<InventoryTaskListDtlResponse> inventoryTaskDtlResponseLiveDataWrapper) {
                switch (inventoryTaskDtlResponseLiveDataWrapper.status) {
                    case LOADING:
                        waitDialog = CreateDialog.waitingDialog(CheckDetailActivity.this);
                        break;
                    case SUCCESS:
                        if (null != waitDialog) {
                            CreateDialog.dismiss(CheckDetailActivity.this, waitDialog);
                        }
                        data = inventoryTaskDtlResponseLiveDataWrapper.data.getDtlVO();
                        binding.tvCardNo.setText(data.getCardNo());
                        binding.tvDeviceNameDevicedetail.setText(data.getCardName());
                        binding.tvProduceNo.setText(data.getProduceNo());
                        //TODO:科室没有加不浅
                        binding.tvRoom.setText(data.getDepartmentName());

                        // ------------编辑状态进来的
                        if (null != data.getId() && !"".equals(data.getId())) {

                            binding.deviceTitle.titleMenuConfirm.setText("修改");
                            binding.rlDeviceStateNodone.setVisibility(View.GONE);
                            binding.rlRemarkNodone.setVisibility(View.GONE);
                            //资产原值
                            binding.rlYuanzhi.setVisibility(View.VISIBLE);
                            if (null != data.getOriginalValue()) {
                                binding.tvOldValue.setText(data.getOriginalValue());
                            } else {
                                binding.tvOldValue.setText("无");
                            }
                            binding.rlOutlookAddedDone.setVisibility(View.VISIBLE);
                            if (null != data.getInventoryStatus()) {
                                //盘点结果
                                binding.tvOutlookAddedStateDevicedetailDone.setText(data.getInventoryStatus());
                            } else {
                                binding.tvOutlookAddedStateDevicedetailDone.setText("无");
                            }
                            binding.rlRemarkDone.setVisibility(View.VISIBLE);
                            if (null != data.getRemarks()) {
                                binding.remarkDone.setText(data.getRemarks());
                            } else {
                                binding.remarkDone.setText("无");
                            }
                            if (null != data.getInventoryUserName()) {
                                binding.tvCheckPeopleDone.setText(data.getInventoryUserName());
                            } else {
                                binding.tvCheckPeopleDone.setText("无");
                            }
                            if (null != data.getInventoryDatetime()) {
                                binding.checkTimeDone.setText(data.getInventoryDatetime());
                            } else {
                                binding.checkTimeDone.setText("无");
                            }
                        } else {
                            binding.rlYuanzhi.setVisibility(View.GONE);
                            binding.rlOutlookAddedDone.setVisibility(View.GONE);
                            binding.rlRemarkDone.setVisibility(View.GONE);
                            binding.rlYuanzhi.setVisibility(View.GONE);

                            binding.rlDeviceStateNodone.setVisibility(View.VISIBLE);
                            binding.rlRemarkNodone.setVisibility(View.VISIBLE);
                            binding.deviceTitle.titleMenuConfirm.setText("保存");
                        }
                        break;
                    case ERROR:
                        if (null != waitDialog) {
                            CreateDialog.dismiss(CheckDetailActivity.this, waitDialog);
                        }
                        handleException(inventoryTaskDtlResponseLiveDataWrapper.error, true);
                        break;
                }
            }
        });

    }

    private void initView() {
//        binding.deviceTitle.titleTextTv.setText("设备盘点详情");
        binding.deviceTitle.titleBackLl.setVisibility(View.VISIBLE);
        binding.deviceTitle.titleBackTv.setText("");
        binding.deviceTitle.titleBackLl.setOnClickListener(this);
//        binding.materialTitle.titleMenuConfirm.setVisibility(View.VISIBLE);
//        binding.deviceTitle.titleMenuConfirm.setText("保存");
        binding.deviceTitle.titleMenuConfirm.setOnClickListener(this);
        taskId = getIntent().getExtras().getString("taskId");
        isDone = getIntent().getExtras().getBoolean("isDone");
        taskDtlId = getIntent().getExtras().getString("taskDtlId");
        data = (InventoryTaskDtlVO) getIntent().getSerializableExtra("data");
        if(isDone){
            binding.deviceTitle.titleMenuConfirm.setVisibility(View.GONE);
            binding.deviceTitle.titleTextTv.setText("设备盘点");
        }else{
            if("".equals(taskDtlId)){
                binding.deviceTitle.titleTextTv.setText("设备盘点详情");
            }else{
                binding.deviceTitle.titleTextTv.setText("设备盘点");
            }
            binding.deviceTitle.titleMenuConfirm.setVisibility(View.VISIBLE);
        }

        binding.shebeizhuangkuang.setText(Html.fromHtml(getString(R.string.divice_notice4)));

        if(null != data){
            binding.tvCardNo.setText(data.getCardNo());
            binding.tvDeviceNameDevicedetail.setText(data.getCardName());
            binding.tvProduceNo.setText(data.getProduceNo());
            //TODO:科室没有加不浅
            if (null != data.getDepartmentName()) {
                binding.tvRoom.setText(data.getDepartmentName());
            } else {
                binding.tvRoom.setText("无");
            }

                // ------------编辑状态进来的      && !"盘盈".equals(data.getInventoryStatus())
                if (null != data.getId() && !"".equals(data.getId())) {
                    if(null != data.getInventoryStatus() && "盘盈".equals(data.getInventoryStatus())) {
                        binding.deviceTitle.titleMenuConfirm.setText("删除");
                    }else{
                        binding.deviceTitle.titleMenuConfirm.setText("修改");
                    }

                    binding.rlDeviceStateNodone.setVisibility(View.GONE);
                    binding.rlRemarkNodone.setVisibility(View.GONE);
                    //资产原值
                    binding.rlYuanzhi.setVisibility(View.VISIBLE);
                    if (null != data.getOriginalValue()) {
                        binding.tvOldValue.setText(data.getOriginalValue());
                    } else {
                        binding.tvOldValue.setText("无");
                    }
                    binding.rlOutlookAddedDone.setVisibility(View.VISIBLE);
                    if (null != data.getInventoryStatus()) {
                        //盘点结果
                        binding.tvOutlookAddedStateDevicedetailDone.setText(data.getInventoryStatus());
                    } else {
                        binding.tvOutlookAddedStateDevicedetailDone.setText("无");
                    }
                    binding.rlRemarkDone.setVisibility(View.VISIBLE);
                    if (null != data.getRemarks()) {
                        binding.remarkDone.setText(data.getRemarks());
                    } else {
                        binding.remarkDone.setText("无");
                    }
                    if (null != data.getInventoryUserName()) {
                        binding.tvCheckPeopleDone.setText(data.getInventoryUserName());
                    } else {
                        binding.tvCheckPeopleDone.setText("无");
                    }
                    if (null != data.getInventoryDatetime()) {
                        binding.checkTimeDone.setText(data.getInventoryDatetime());
                    } else {
                        binding.checkTimeDone.setText("无");
                    }
                } else {
                    binding.rlYuanzhi.setVisibility(View.GONE);
                    binding.rlOutlookAddedDone.setVisibility(View.GONE);
                    binding.rlRemarkDone.setVisibility(View.GONE);
                    binding.rlYuanzhi.setVisibility(View.GONE);

                    binding.rlDeviceStateNodone.setVisibility(View.VISIBLE);
                    binding.rlRemarkNodone.setVisibility(View.VISIBLE);
                    binding.deviceTitle.titleMenuConfirm.setText("保存");
                }
        }



    }

    private void initListener() {
        binding.rlDeviceStateNodone.setOnClickListener(this);
        binding.remark.addTextChangedListener(new MyTextWatcher(binding.tvLimit, binding.remark, 25, CheckDetailActivity.this));
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (!isDone) {
            closeBroadCast();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (!isDone) {
            openBroadCast();
        }
//        viewModel.getDetail(taskId, taskDtlId);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.rl_device_state_nodone:
                if (null == mMenuPop) {
                    mMenuPop = new BottomMenuPopupExist(CheckDetailActivity.this, itemsOnClick_OutAdded, binding.tvDeviceStateDevicedetail.getText().toString());
                    mMenuPop.setOnDismissListener(new PopupWindow.OnDismissListener() {
                        @Override
                        public void onDismiss() {
                            AlphaManager.backgroundAlpha(1f, CheckDetailActivity.this);
                        }
                    });
                }
                //显示窗口
                mMenuPop.showAtLocation(CheckDetailActivity.this.findViewById(R.id.main), Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0); //设置layout在PopupWindow中显示的位置
                AlphaManager.backgroundAlpha(0.7f, CheckDetailActivity.this);
                break;
            case R.id.title_back_ll:
                finish();
                break;

            case R.id.title_menu_confirm:
                //第一次保存
                if (binding.deviceTitle.titleMenuConfirm.getVisibility() == View.VISIBLE && "保存".equals(binding.deviceTitle.titleMenuConfirm.getText())) {
                    submit();
                    return;
                } else if (binding.deviceTitle.titleMenuConfirm.getVisibility() == View.VISIBLE && "修改".equals(binding.deviceTitle.titleMenuConfirm.getText())) {
                    binding.rlYuanzhi.setVisibility(View.GONE);
                    binding.rlOutlookAddedDone.setVisibility(View.GONE);
                    binding.rlRemarkDone.setVisibility(View.GONE);
                    binding.rlYuanzhi.setVisibility(View.GONE);

                   binding.rlDeviceStateNodone.setVisibility(View.VISIBLE);
                    binding.rlRemarkNodone.setVisibility(View.VISIBLE);
                    binding.deviceTitle.titleMenuConfirm.setText("保存");
                    if (null != data && null != data.getRemarks() && !"".equals(data.getRemarks())) {
                        binding.remark.setText(data.getRemarks());
                        binding.remark.setSelection(data.getRemarks().length());
                    }
                }else if(binding.deviceTitle.titleMenuConfirm.getVisibility() == View.VISIBLE && "删除".equals(binding.deviceTitle.titleMenuConfirm.getText())){
                    SubmitCheckTaskListDetailRequest request =  new SubmitCheckTaskListDetailRequest();
                    request.setId(data.getId());
                    if (null != data.getId() && !"".equals(data.getId())) {
                        request.setId(data.getId());
                    }
                    if (null != taskId && !"".equals(taskId)) {
                        request.setBillId(taskId);
                    }
                    request.setIsDeleted("y");
                    viewModel.submitDetail(request,true,"删除成功").observe(this, new Observer<LiveDataWrapper<Boolean>>() {
                        @Override
                        public void onChanged(@Nullable LiveDataWrapper<Boolean> booleanLiveDataWrapper) {
                            switch (booleanLiveDataWrapper.status) {
                                case LOADING:
                                    waitDialog = CreateDialog.waitingDialog(CheckDetailActivity.this);
                                    break;
                                case SUCCESS:
                                    waitDialog.dismiss();
                                    finish();
                                    break;
                                case ERROR:
                                    waitDialog.dismiss();
                                    mDialog = CreateDialog.submitDialog(CheckDetailActivity.this, "删除失败", "服务器问题", 102, new View.OnClickListener() {
                                        @Override
                                        public void onClick(View v) {
                                            if (null != mDialog) {
                                                mDialog.cancel();
                                            }
                                            finish();
                                        }
                                    }, "确定");
                                    break;
                            }
                        }
                    });
                }
                break;
        }
    }

    public void submit() {
        request = new SubmitCheckTaskListDetailRequest();
        //判断选择框是否被操作过   &&  否的话   要进行备注，否则不让提交
        if ("".equals(binding.tvDeviceStateDevicedetail.getText().toString())) {
            //提示请选择是否存在
            ToastUtil.toastWarning(CheckDetailActivity.this, "请选择设备是否存在", -1);
            return;
        }
        if ("否".equals(binding.tvDeviceStateDevicedetail.getText().toString()) &&
                "".equals(binding.remark.getText().toString().trim())
                ) {
            //提示填写备注
            ToastUtil.toastWarning(CheckDetailActivity.this, "请填写备注", -1);
            return;
        }
        if (null != data) {

            request.setId(data.getId());

            if (null != taskId && !"".equals(taskId)) {
                request.setBillId(taskId);
            }
            if(null != data.getDepartmentId()){
                request.setDepartmentId(data.getDepartmentId());
            }
            if (null != data.getCardNo() && !"".equals(data.getCardNo())) {
                request.setCardNo(data.getCardNo());
            }
            if (null != data.getCardVersionId() && !"".equals(data.getCardVersionId())) {
                request.setCardVersionId(data.getCardVersionId());
            }
            request.setBookQuantity("1");
            if ("是".equals(binding.tvDeviceStateDevicedetail.getText().toString())) {
                request.setInventoryQuantity("1");
            } else if ("否".equals(binding.tvDeviceStateDevicedetail.getText().toString())) {
                request.setInventoryQuantity("0");
            }
                // remark 备注  ----以防乱码
                String remark = binding.remark.getText().toString().trim();
                String encode = null;
                try {
                    encode = URLEncoder.encode(remark, "utf-8");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                    request.setRemarks(encode);

        }
        viewModel.submitDetail(request,true,"提交成功").observe(this, new Observer<LiveDataWrapper<Boolean>>() {
            @Override
            public void onChanged(@Nullable LiveDataWrapper<Boolean> booleanLiveDataWrapper) {
                switch (booleanLiveDataWrapper.status) {
                    case LOADING:
                        waitDialog = CreateDialog.waitingDialog(CheckDetailActivity.this);
                        break;
                    case SUCCESS:
                        waitDialog.dismiss();
                        finish();
                        break;
                    case ERROR:
                        waitDialog.dismiss();
                        mDialog = CreateDialog.submitDialog(CheckDetailActivity.this, "提交失败", "服务器问题", 102, new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                if (null != mDialog) {
                                    mDialog.cancel();
                                }
                                finish();
                            }
                        }, "确定");
                        break;
                }
            }
        });
    }


    //为弹出窗口实现监听类
    private View.OnClickListener itemsOnClick_OutAdded = new View.OnClickListener() {

        public void onClick(View v) {
            if (null != mMenuPop && mMenuPop.isShowing()) {
                mMenuPop.dismiss();
            }
            switch (v.getId()) {
                case R.id.rl_normal:
                    binding.tvDeviceStateDevicedetail.setText("是");
                    mMenuPop.setRight("是");
                    AlphaManager.backgroundAlpha(1.0f, CheckDetailActivity.this);
                    if ("是".equals(binding.tvDeviceStateDevicedetail.getText().toString().trim())
                            || "请选择".equals(binding.tvDeviceStateDevicedetail.getText().toString().trim())) {
                        binding.beizhu.setText("备注");
                    }
                    break;
                case R.id.rl_error:
                    binding.tvDeviceStateDevicedetail.setText("否");
                    mMenuPop.setRight("否");
                    AlphaManager.backgroundAlpha(1.0f, CheckDetailActivity.this);
                    binding.beizhu.setText(Html.fromHtml(getString(R.string.divice_notice3)));
//                    binding.beizhu.setText("* 备注");
                    break;
            }
        }
    };

    public boolean isUUID(String qrCode) {
        if (null != qrCode && !"".equals(qrCode)) {
            return MD5Util.IsUUID(qrCode);
        }
        return true;
    }

    @Override
    protected void brodcast(Context context, String msg) {
        super.brodcast(context, msg);
        String qrCode = msg;
        if (binding.deviceTitle.titleMenuConfirm.getVisibility() == View.VISIBLE && "保存".equals(binding.deviceTitle.titleMenuConfirm.getText())) {
            request = new SubmitCheckTaskListDetailRequest();
            //判断选择框是否被操作过   &&  否的话   要进行备注，否则不让提交
            if ("".equals(binding.tvDeviceStateDevicedetail.getText().toString())) {
                //提示请选择是否存在
                ToastUtil.toastWarning(CheckDetailActivity.this, "请选择设备是否存在", -1);
                return;
            }
            if ("否".equals(binding.tvDeviceStateDevicedetail.getText().toString()) &&
                    "".equals(binding.remark.getText().toString().trim())
                    ) {
                //提示填写备注
                ToastUtil.toastWarning(CheckDetailActivity.this, "请填写备注", -1);
                return;
            }
            if (null != data) {
                request.setId(data.getId());
                if (null != taskId && !"".equals(taskId)) {
                    request.setBillId(taskId);
                }
                if (null != data.getCardNo() && !"".equals(data.getCardNo())) {
                    request.setCardNo(data.getCardNo());
                }
                if (null != data.getCardVersionId() && !"".equals(data.getCardVersionId())) {
                    request.setCardVersionId(data.getCardVersionId());
                }
                request.setBookQuantity("1");
                if ("是".equals(binding.tvDeviceStateDevicedetail.getText().toString())) {
                    request.setInventoryQuantity("1");
                } else if ("否".equals(binding.tvDeviceStateDevicedetail.getText().toString())) {
                    request.setInventoryQuantity("0");
                }
                    // remark 备注  ----以防乱码
                    String remark = binding.remark.getText().toString().trim();
                    String encode = null;
                    try {
                        encode = URLEncoder.encode(remark, "utf-8");
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                    request.setRemarks(encode);

            }
            viewModel.submitDetail(request ,false,"提交").observe(this, new Observer<LiveDataWrapper<Boolean>>() {
                @Override
                public void onChanged(@Nullable LiveDataWrapper<Boolean> booleanLiveDataWrapper) {
                    switch (booleanLiveDataWrapper.status) {
                        case LOADING:
                            waitDialog = CreateDialog.waitingDialog(CheckDetailActivity.this);
                            break;
                        case SUCCESS:
                            waitDialog.dismiss();
                            if (!isUUID(qrCode)) {
                                //不符合UUID  误操作扫描非盘点二维码  跳转页面 显示扫描错误
                                Intent intent = new Intent(CheckDetailActivity.this, AbNormalActivity.class);
                                intent.putExtra("error", 0);
                                startActivity(intent);
                                finish();
                            } else {
                                // 请求服务器去更新状态   1.成功 2.失败 失败进行跳转显示不在巡检范围
                                if (null != taskId && !"".equals(taskId)) {
                                    viewModel.updateByBroad(qrCode, taskId);
                                }
                            }
                            break;
                        case ERROR:
                            waitDialog.dismiss();
                            mDialog = CreateDialog.submitDialog(CheckDetailActivity.this, "提交失败", "服务器问题", 102, new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    if (null != mDialog) {
                                        mDialog.cancel();
                                    }
                                    finish();
                                }
                            }, "确定");
                            break;
                    }
                }
            });
        }
        if (binding.deviceTitle.titleMenuConfirm.getVisibility() == View.VISIBLE && "修改".equals(binding.deviceTitle.titleMenuConfirm.getText()) || "删除".equals(binding.deviceTitle.titleMenuConfirm.getText())) {
            if (!isUUID(qrCode)) {
                //不符合UUID  误操作扫描非盘点二维码  跳转页面 显示扫描错误
                Intent intent = new Intent(CheckDetailActivity.this, AbNormalActivity.class);
                intent.putExtra("error", 0);
                startActivity(intent);
                finish();
            } else {
                // 请求服务器去更新状态   1.成功 2.失败 失败进行跳转显示不在巡检范围
                if (null != taskId && !"".equals(taskId)) {
                    viewModel.updateByBroad(qrCode, taskId);
                }
            }
        }


    }
}
